package com.xintool.window.Buttons;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class Button_xxl extends ButtonFactory{

    // 添加窗口实例跟踪
    private static JFrame studyFrame;
    //声明resultArea为成员变量
    private JTextArea resultArea;

    @Override
    public JButton showButton() {
        // 利用按钮工厂创建按钮实例
        JButton button_xxl = ButtonFactory.getButton("学习力");//按钮显示文本为“学习力”

        //添加点击事件监听
        button_xxl.addActionListener(e -> createMainWindow());
        return button_xxl;
    }

    //创建主面板
    public void  createMainWindow(){

        // 检查窗口是否已经存在
        if (studyFrame != null && studyFrame.isDisplayable()) {
            // 如果窗口存在则带到前台
            studyFrame.toFront();
            return;
        }

        //创建窗口实例frame
        studyFrame = new JFrame("学习力地点查询");
        //设置窗口大小
        studyFrame.setSize(400, 270);
        // 禁止调整窗口大小
        studyFrame.setResizable(false);
        // 窗口居中显示
        studyFrame.setLocationRelativeTo(null);
        // 设置关闭窗口时退出程序
        studyFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        studyFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                // 窗口关闭时释放引用
                studyFrame = null;
            }
        });

        //添加面板
        studyFrame.add(createMainPanel());
        studyFrame.setVisible(true);
    }

    //创建主面板
    public JPanel createMainPanel(){
        //创建面板
        JPanel panel = new JPanel(new GridLayout(2,1,10,20));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        //添加选择面板
        panel.add(choosePanel(),BorderLayout.NORTH);
        //添加结果面板
        panel.add(result(),BorderLayout.CENTER);

        return panel;
    }

    //创建选择学习力面板
    public JPanel choosePanel(){
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER,5,10));
        panel.setBorder(new TitledBorder("选择要刷取的学习力"));

        JCheckBox cb1 = new JCheckBox("体力");
        JCheckBox cb2 = new JCheckBox("攻击");
        JCheckBox cb3 = new JCheckBox("防御");
        JCheckBox cb4 = new JCheckBox("特攻");
        JCheckBox cb5 = new JCheckBox("特防");
        JCheckBox cb6 = new JCheckBox("速度");
        JCheckBox wildOnlyCheckBox = new JCheckBox("仅野生普通精灵", true);
        JButton queryButton = new JButton("查询");

        panel.add(cb1);
        panel.add(cb2);
        panel.add(cb3);
        panel.add(cb4);
        panel.add(cb5);
        panel.add(cb6);
        panel.add(wildOnlyCheckBox);
        panel.add(queryButton);

        queryButton.addActionListener(event -> query(cb1,cb2,cb3,cb4,cb5,cb6,wildOnlyCheckBox));
        return panel;
    }

    //更新查询按钮的ActionListener，实现数据读取和筛选
    public void query(JCheckBox cb1,JCheckBox cb2,JCheckBox cb3,JCheckBox cb4,JCheckBox cb5,JCheckBox cb6,
                      JCheckBox wildOnlyCheckBox){
        // 获取选中的属性
        List<String> selectedAttrs = new ArrayList<String>();
        if (cb1.isSelected()) selectedAttrs.add("体力");
        if (cb2.isSelected()) selectedAttrs.add("攻击");
        if (cb3.isSelected()) selectedAttrs.add("防御");
        if (cb4.isSelected()) selectedAttrs.add("特攻");
        if (cb5.isSelected()) selectedAttrs.add("特防");
        if (cb6.isSelected()) selectedAttrs.add("速度");

        // 验证选择数量
        if (selectedAttrs.size() > 2) {
            JOptionPane.showMessageDialog(studyFrame, "最多选择2个属性！");
            return;
        }
        if (selectedAttrs.isEmpty()) {
            JOptionPane.showMessageDialog(studyFrame, "请至少选择1个属性！");
            return;
        }

        // 读取并处理数据
        List<String> results = new ArrayList<>();

        try  {
            Path dataDir = Paths.get(System.getProperty("user.dir"), "data");
            Path filePath = dataDir.resolve("monsters.txt");
            BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8);
            // 明确的路径校验
            if (!Files.exists(filePath)) {
                resultArea.setText("数据文件不存在！\n完整路径：" + filePath.toAbsolutePath());
                return;
            }
            if (!Files.isReadable(filePath)) {
                resultArea.setText("文件无法读取：无权限");
                return;
            }
            String line;
            while ((line = reader.readLine()) != null) {
                String[] fields = line.split(",", -1);
                if (fields.length >= 4) {
                    String id = fields[0].trim();
                    String name = fields[1].trim();
                    String attr = fields[3].trim();
                    String location = fields.length > 4 ? fields[4].trim() : "";

                    // 属性匹配检查
                    boolean attrMatch = selectedAttrs.stream().allMatch(attr::contains);

                    // 野生检查
                    boolean isWildValid = !wildOnlyCheckBox.isSelected() || !location.isEmpty();

                    if (attrMatch && isWildValid) {
                        String locationText = location.isEmpty() ? "" : "，位于" + location;
                        results.add(String.format("%s,%s,%s%s", id, name, attr, locationText));
                    }
                }
            }
            // 更新结果
            resultArea.setText(String.join("\n", results));
            resultArea.setCaretPosition(0); // 将文本光标定位到开头
            resultArea.scrollRectToVisible(new Rectangle(0, 0, 1, 1)); // 强制滚动到顶部
        } catch (Exception e) {
            resultArea.setText("数据加载失败");
            e.printStackTrace();
        }
    }

    public JPanel result(){
        JPanel panel = new JPanel(new BorderLayout());
        resultArea = new JTextArea();
        resultArea.setEditable(false);
        panel.add(new JScrollPane(resultArea));
        return panel;
    }
}

